var supplierObj = [];
var limit = 15;
var tid;
var orgObj = convertOrgToObj(orgList);
layui.use(['laypage', 'table', 'form'], function(){
    var table = layui.table;
    var form = layui.form;

    $(".add-takeTime").datePicker({
        format:"YYYY-MM-DD HH:mm:ss",
        singleDate:true,  //单选日期
    });

    let todoCols = [
        [
            {field: 'id', title: '标识', width:80, align: 'center', hide: true}
            ,{field: 'orgId', title: '公司名称', width:160, fixed: 'left', align: 'center',templet:function (val) {
                return orgObj[val.orgId];
            }}
            ,{field: 'supplierId', title: '供应商标识', width:80, align: 'center', hide: true}
            ,{field: 'supplier', title: '供应商', width: 200, fixed: 'left',align: 'center',templet: function (val) {
                if (isNull(val.supplier)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.supplier + '</div>';
            }}
            ,{field: 'today', title: '结算时间', width: 160, fixed: 'left',align: 'center',templet: function (val) {
                if (isNull(val.today)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.today + '</div>';
            }}
            ,{field: 'startTime', title: '报表开始时间', width: 160, fixed: 'left',align: 'center',templet: function (val) {
                if (isNull(val.startTime)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.startTime + '</div>';
            }}
            ,{field: 'endTime', title: '报表结束时间', width: 160, fixed: 'left',align: 'center',templet: function (val) {
                if (isNull(val.endTime)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.endTime + '</div>';
            }}
            ,{field: 'materialId', title: '材料标识', width:80, align: 'center', hide: true}
            ,{field: 'material', title: '材料名称', width: 160, fixed: 'left',align: 'center',templet: function (val) {
                if (isNull(val.material)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.material + '</div>';
            }}
            ,{field: 'takeTime', title: '价格生效时间', width: 160, fixed: 'left',align: 'center'}
            ,{field: 'price', title: '单价', width: 80, fixed: 'left',align: 'center'}
            ,{field: 'supplierWeight', title: '供方净重', width: 100, fixed: 'left',align: 'center'}
            ,{field: 'weight', title: '过磅净重', width: 100, fixed: 'left',align: 'center'}
            ,{field: 'type', title: '类型', width:200, align: 'center', templet:function (val) {
                if (val.type == 0)
                    return '主材';
                else
                if (val.type == 1)
                    return '运输车';
                else
                if (val.type == 2)
                    return '材料销售';
                else
                if (val.type == 3)
                    return '运输船';
                else
                    return '加工';
            }}
            ,{field: 'priceType', title: '费用类型', width:200, align: 'center', templet:function (val) {
                if (val.priceType == 0)
                    return '结算';
                else
                    return '补贴';
            }}
            ,{field: 'isBill', title: '是否结算', width:200, align: 'center', templet:function (val) {
                if (val.isBill == 0)
                    return '结算';
                else
                    return '不结算';
            }}
            ,{field: 'isCheck', title: '材料是否审核', width:100, align: 'center', templet:function (val) {
                if (val.isCheck == 0)
                    return '未审核';
                else
                    return '已审核';
            }}
            ,{field: 'checker', title: '审核人', width: 100, align: 'center'}
            ,{field: 'checkTime', title: '审核时间', width: 160, align: 'center'}
            ,{field: 'isFinance', title: '财务是否审核', width:100, align: 'center', templet:function (val) {
                if (val.isFinance == 0)
                    return '未审核';
                else
                    return '已审核';
            }}
            ,{field: 'finance', title: '财务审核人', width: 100, align: 'center'}
            ,{field: 'financeTime', title: '财务审核时间', width: 160, align: 'center'}
            ,{field: 'status', title: '状态', width:200, align: 'center', templet:function (val) {
                if (val.status == 0)
                    return '启用';
                else
                    return '禁用';
            }}
            ,{field: 'remark', title: '审核备注', width: 580, align: 'center',templet: function (val) {
                if (isNull(val.remark)) {
                    return "";
                }
                return '<div style="white-space: pre-wrap;">' + val.remark + '</div>';
            }}
            ,{field: 'creator', title: '创建人', width: 240, align: 'center'}
            ,{field: 'createTime', title: '创建时间', width: 240, align: 'center'}
            ,{fixed: 'right', title:'操作', width: 260, align:'center', templet:function (val) {
                var str = '<a lay-event="detail" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-primary">详情</a>';
                if (val.status == 0 && val.isCheck == 0 && val.isFinance == 0){
                    str += '<a lay-event="edit" href="javascript:void(0)" class="layui-btn layui-btn-xs">编辑</a>';
                    str += '<a lay-event="delete" href="javascript:void(0)" class="layui-btn layui-btn-xs layui-btn-danger">作废</a>';
                }
                if (val.status == 0 && val.isCheck == 0 && isCheckVal == 1 ){
                    str += '<a lay-event="check" href="javascript:void(0)" class="layui-btn layui-btn-xs">材料审核</a>';
                }
                if (val.status == 0 && val.isCheck == 1 && val.isFinance == 0 && isFinanceVal == 1 ){
                    str += '<a lay-event="finance" href="javascript:void(0)" class="layui-btn layui-btn-xs">财务审核</a>';
                }
                return str;
            }}
        ]
    ];

    table.render({
        elem: '#body-list'
        ,url: '/main-material-bill/page'
        ,method: 'post'
        ,page: true
        ,contentType: 'application/json'
        ,cols: todoCols
        ,limit: limit
        ,limits: [15,30,50,100]
        ,request: {
            pageName: 'curr' //页码的参数名称，默认：page
            ,limitName: 'limit' //每页数据量的参数名，默认：limit
        }
        ,where: {
            offset: 0,
            limit: limit,
            orgId:$('.search-origin').val(),
        }
        ,parseData: function(res){ //res 即为原始返回的数据
            console.log(res);
            if (res.code == 0 && res.data != null) {
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            } else {
                return {
                    "code": res.code, //解析接口状态
                    "msg": '没有任何数据', //解析提示文本
                    "count": 0, //解析数据长度
                    "data": '' //解析数据列表
                };
            }
        }
    });

    //监听行工具事件
    table.on('tool(body-list)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"

        var data = obj.data //获得当前行数据
            ,layEvent = obj.event; //获得 lay-event 对应的值
        if(layEvent === 'delete'){
            var id = data.id;
            var status = data.status;
            var tip = '是否要启用？';
            if (status == 0)
                tip = '是否要作废？';
            layer.confirm(tip, {
                btn: ['确定', '取消']
            }, function(index, layero){
                var updateStatus = 0;
                if (status == 0)
                    updateStatus = 1;
                var option =  '{"id": '+id+', "status":'+updateStatus+'}';
                save(option, "/main-material-bill/updatestatus");
            }, function(index){
            });
        }else if(layEvent === 'edit'){
            tid = data.id;
            $("#updateTitle").text("修改主材材料结算信息表");
            $('.updateModal').show();
            $('.update-search-origin').val(data.orgId);
            getMaterialList('{"orgId": '+data.orgId+', "materialId": '+data.materialId+'}');
            getSupplierList('{"orgId": '+data.orgId+',"supplierId": '+data.supplierId+' }');
            getToDayList();
            $(".update-startTime").val(data.startTime);
            $(".update-endTime").val(data.endTime);
            $(".update-supplierWeight").val(data.supplierWeight);
            $(".update-weight").val(data.weight);
            $(".update-takeTime").val(data.takeTime);
            $(".update-price").val(data.price);
            $(".update-priceType").val(data.priceType);
            $(".update-isBill").val(data.isBill);
            $(".update-today").val(data.today);
            $("#updateBtn").show();
            form.render();
        } else  if(layEvent === 'detail'){
            $("#updateTitle").text("查看主材材料结算信息表");
            $('.updateModal').show();
            $('.update-search-origin').val(data.orgId);
            getMaterialList('{"orgId": '+data.orgId+', "materialId": '+data.materialId+'}');
            getSupplierList('{"orgId": '+data.orgId+',"supplierId": '+data.supplierId+' }');
            getToDayList();
            $(".update-startTime").val(data.startTime);
            $(".update-endTime").val(data.endTime);
            $(".update-supplierWeight").val(data.supplierWeight);
            $(".update-weight").val(data.weight);
            $(".update-takeTime").val(data.takeTime);
            $(".update-price").val(data.price);
            $(".update-priceType").val(data.priceType);
            $(".update-isBill").val(data.isBill);
            $(".update-today").val(data.today);
            $("#updateBtn").hide();
            form.render();
        }else if(layEvent === 'check'){
            var id = data.id;
            var tip = '<p style="color: red">请仔细审查资料，确认是否审核通过？</p>';
            layer.confirm(tip, {
                title: '审核提示',
                btn: ['审核通过', '审核取消']
            }, function(index, layero){
                var option =  '{"id": '+id+', "type":"check"}';
                save(option, "/main-material-bill/auditdata");
            }, function(index){
            });
        }else if(layEvent === 'finance'){
            var id = data.id;
            var tip = '<p style="color: red">请仔细审查资料，确认是否审核通过？</p>';
            layer.confirm(tip, {
                title: '审核提示',
                btn: ['审核通过', '审核取消']
            }, function(index, layero){
                var option =  '{"id": '+id+', "type":"finance"}';
                save(option, "/main-material-bill/auditdata");
            }, function(index){
            });
        }
    });

    form.on('select(search-status)', function(data) {
        $(".btn-query").trigger("click");
    });

    form.on('select(search-supplier)', function(data) {
        $(".btn-query").trigger("click");
    });

    form.on('select(search-material)', function(data) {
        $(".btn-query").trigger("click");
    });

    form.on('select(search-origin)', function(data) {
        getSupplierByOrgId();
        getMaterialByOrgId();
        $(".btn-query").trigger("click");
    });

    $('.btn-query').on('click', function () {//搜索按钮
        var searchVal = $('.search-text').val();
        var status = $('.search-status').val();
        var orgId = $('.search-origin').val();
        var supplierId = $('.search-supplier').val();
        var materialId = $('.search-material').val();

        var option = {page:1,limit:limit};
        if (!isNull(searchVal))
            option['searchVal'] = searchVal;
        if (!isNull(orgId))
            option['orgId'] = orgId;
        if (!isNull(status))
            option['status'] = status;
        if (!isNull(supplierId))
            option['supplierId'] = supplierId;
        if (!isNull(materialId))
            option['materialId'] = materialId;
        table.reload('body-list', {
            where: option
        });
    });


    function save(option, url) {//新增或修改
        var loading = layer.load(1);
        console.log(option);
        $.ajax({
            url: url,
            type: 'POST',
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            data: option,
            timeout: 30000,
            success: function(res) {
                layer.close(loading);
                if(res.code == 0) {
                    layer.msg("保存成功!");
                    table.reload('body-list', { where: {offset:0,curr:1,
                            limit: limit,
                            orgId:$('.search-origin').val() }});
                    $(".addModal").hide();
                    $(".addModal input").val("");
                    $(".addModal select").val("");
                    $(".addModal textarea").val("");
                    $(".updateModal").hide();
                    $(".updateModal input").val("");
                    $(".updateModal select").val("");
                    $(".updateModal textarea").val("");
                    form.render();
                } else {
                    layer.msg(res.msg);
                    return;
                }
            },
            error: function(res) {
                layer.msg("请求失败，请稍后再试！");
                layer.close(loading);
                return;
            },
            complete: function(XMLHttpRequest, status) {
                if(status == 'timeout') {
                    layer.msg("请求超时，请稍后再试！");
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    //初始化执行一次
    getSupplierByOrgId();
    getMaterialByOrgId();
    getToDayList();
    //加载供应商信息
    function getSupplierByOrgId() {
        var obj = '{"orgId": '+$(".search-origin").val()+'}';
        var loading = layer.load(1);
        $.ajax({
            url: '/main-material-bill/getSupplierList',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择供应商</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.search-supplier').html(html);
                } else {
                    $('.search-supplier').html('<option value="">暂无数据</option>');
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    //加载材料下拉框
    function getMaterialByOrgId() {
        var obj = '{"orgId": '+$(".search-origin").val()+'}';
        var loading = layer.load(1);
        $.ajax({
            url: '/main-material-bill/getMaterialList',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择材料</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.search-material').html(html);
                } else {
                    $('.search-material').html('<option value="">暂无数据</option>');
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }
    //关闭编辑页面
    $(".updateModal .close").on("click", function() {
        $(".updateModal").hide();
        $(".updateModal-body input").val("");
        $(".updateModal select").val("");
        $(".updateModal textarea").val("");
        form.render();
        tid = -1;
    });

    //新增页面选择类型
    form.on('select(add-search-origin)', function(data) {
        getSupplierList('{"orgId": '+$(".add-search-origin").val()+'}');
        getMaterialList('{"orgId": '+$(".add-search-origin").val()+'}');
    });


    form.on('select(add-today)', function(data) {
        $(".add-startTime").val($(".addModal .add-today").find("option:selected").attr('data-start'));
        $(".add-endTime").val($(".addModal .add-today").find("option:selected").attr('data-end'));
    });

    //打开新增页面
    $('.btn-add').on('click', function () {//新增流程
        $('.addModal').show();
        getSupplierList('{"orgId": '+$(".add-search-origin").val()+'}');
        getMaterialList('{"orgId": '+$(".add-search-origin").val()+'}');
        getToDayList();
    });

    //关闭新增页面
    $(".addModal .close").on("click", function () {//关闭新增流程窗口
        $(".addModal").hide();
        $(".addModal input").val("");
        $(".addModal select").val("");
        $(".addModal textarea").val("");
        form.render();
    });

    //新增
    form.on('submit(addBtns)', function () {
        var option = null;
        var orgName = $.trim($(".addModal .add-search-origin").find("option:selected").text());//公司名称
        var orgId = $(".add-search-origin").val();
        var today = $(".add-today").val();
        var supplierId = $(".add-supplier").val();
        var supplier = $.trim($(".addModal .add-supplier").find("option:selected").text());//供应商名称
        var materialId = $(".add-material").val();
        var material = $.trim($(".addModal .add-material").find("option:selected").text());//供应商名称
        var startTime = $(".add-startTime").val();
        var endTime = $(".add-endTime").val();
        var supplierWeight = $(".add-supplierWeight").val();
        var weight = $(".add-weight").val();
        var takeTime = $(".add-takeTime").val();
        var price = $(".add-price").val();
        var priceType = $(".add-priceType").val();
        var isBill = $(".add-isBill").val();
        option = '{"orgId":'+orgId+',"orgName":"'+orgName+'","today":"'+today+'","supplierId":'+supplierId+',"supplier":"'+supplier+'","materialId":'+materialId+',"material":"'+material+'","startTime":"'+startTime+'","endTime":"'+endTime+'","supplierWeight":"'+supplierWeight+'","weight":"'+weight+'","takeTime":"'+takeTime+'","price":"'+price+'","priceType":"'+priceType+'","isBill":"'+isBill+'"}';
        save(option,"/main-material-bill/save");
    });

    //新增页面选择类型
    form.on('select(update-search-origin)', function(data) {
        getSupplierList('{"orgId": '+$(".update-search-origin").val()+'}');
        getMaterialList('{"orgId": '+$(".update-search-origin").val()+'}');
    });


    form.on('select(update-today)', function(data) {
        $(".update-startTime").val($(".updateModal .update-today").find("option:selected").attr('data-start'));
        $(".update-endTime").val($(".updateModal .update-today").find("option:selected").attr('data-end'));
    });

    form.on('submit(updateBtns)', function() {
        var options = null;
        var orgName = $.trim($(".updateModal .update-search-origin").find("option:selected").text());//公司名称
        var orgId = $(".update-search-origin").val();
        var today = $(".update-today").val();
        var supplierId = $(".update-supplier").val();
        var supplier = $.trim($(".updateModal .update-supplier").find("option:selected").text());//供应商名称
        var materialId = $(".update-material").val();
        var material = $.trim($(".updateModal .update-material").find("option:selected").text());//供应商名称
        var startTime = $(".update-startTime").val();
        var endTime = $(".update-endTime").val();
        var supplierWeight = $(".update-supplierWeight").val();
        var weight = $(".update-weight").val();
        var takeTime = $(".update-takeTime").val();
        var price = $(".update-price").val();
        var priceType = $(".update-priceType").val();
        var isBill = $(".update-isBill").val();
        options = '{"id":'+tid+',"orgId":'+orgId+',"orgName":"'+orgName+'","today":"'+today+'","supplierId":'+supplierId+',"supplier":"'+supplier+'","materialId":'+materialId+',"material":"'+material+'","startTime":"'+startTime+'","endTime":"'+endTime+'","supplierWeight":"'+supplierWeight+'","weight":"'+weight+'","takeTime":"'+takeTime+'","price":"'+price+'","priceType":"'+priceType+'","isBill":"'+isBill+'"}'
        if (isNull(tid) || tid == -1) {
            layer.msg("获取修改信息错误,请刷新再试！");
            return ;
        }
        save(options, "/main-material-bill/update");
    });

    //加载供应商信息
    function getSupplierList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/main-material-bill/getSupplierList',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择供应商</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.-supplier').html(html);
                    $('.update-supplier').html(html);
                } else {
                    $('.add-supplier').html('<option value="">暂无数据</option>');
                    $('.update-supplier').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj)){
                    var objVal = $.parseJSON(obj);
                    if(!isNull(objVal.supplierId)) {
                        $('.update-supplier').val(objVal.supplierId+'');
                    }
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    //获取单位关联的材料类型信息
    function getMaterialList(obj) {
        var loading = layer.load(1);
        $.ajax({
            url: '/main-material-bill/getMaterialList',
            type: 'post',
            dataType: 'json',
            timeout: 30000,
            data: obj,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            contentType: 'application/json',
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '<option value="">选择材料</option>';
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.id + '">' + v.name + '</option>';
                    });
                    $('.add-material').html(html);
                    $('.update-material').html(html);
                } else {
                    $('.add-material').html('<option value="">暂无数据</option>');
                    $('.update-material').html('<option value="">暂无数据</option>');
                }
                if (!isNull(obj)){
                    var objVal = $.parseJSON(obj);
                    if(!isNull(objVal.materialId)) {
                        $('.update-material').val(objVal.materialId+'');
                    }
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }

    function getToDayList() {
        var loading = layer.load(1);
        $.ajax({
            url: '/main-material-bill/getToDayList',
            type: 'get',
            timeout: 30000,
            success: function (res) {
                layer.close(loading);
                if (res.code == 0 && res.data != null && res.data.length > 0) {
                    var data = res.data;
                    var html = '';
                    html += '';
                    $(".add-startTime").val(data[0].startTime);
                    $(".add-endTime").val(data[0].endTime);
                    $.each(data, function (i, v) {
                        html += '<option value="' + v.today + '" data-value = "'+v.today+'" data-start = "'+v.startTime+'" data-end = "'+v.endTime+'">' + v.today + '</option>';
                    });
                    $('.add-today').html(html);
                    $('.update-today').html(html);
                } else {
                    $('.add-today').html('<option value="">暂无数据</option>');
                    $('.update').html('<option value="">暂无数据</option>');
                }
                form.render();
            },
            error: function (res) {
                layer.close(loading);
                return;
            },
            complete: function (XMLHttpRequest, status) {
                if (status == 'timeout') {
                    layer.close(loading);
                    return;
                }
            }
        })
    }


    $(document).keyup(function (event) {
        if (event.keyCode == 13) {
            $(".btn-query").trigger("click");
        }
    });
});